package com.example.dingtalklogin.manager.dingtalk;

import com.example.dingtalklogin.common.config.DingtalkProperties;
import com.example.dingtalklogin.event.DingtalkTokenRefreshEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * token管理器
 *
 * @author xuzhen97
 */
@Component
public class AccessTokenManager {

    private String token;

    private DingtalkProperties dingtalkProperties;
    private DingtalkTokenClient dingtalkTokenClient;

    @Autowired
    public AccessTokenManager(DingtalkProperties dingtalkProperties
            , DingtalkTokenClient dingtalkTokenClient) {
        this.dingtalkProperties = dingtalkProperties;
        this.dingtalkTokenClient = dingtalkTokenClient;
    }

    /**
     * 获取企业token
     *
     * @return
     */
    public String getToken() {
        return token;
    }

    /**
     * 刷新企业token
     */
    public synchronized void refreshToken() {
        EnterpriseTokenResponse token = dingtalkTokenClient
                .getToken(dingtalkProperties.getAppKey(), dingtalkProperties.getAppSecret());
        this.token = token.getAccessToken();
    }

    /**
     * 监听刷新token事件调用刷新token方法
     * @param event
     */
    @EventListener
    public void processRefreshTokenEvent(DingtalkTokenRefreshEvent event){
        refreshToken();
    }

    /**
     * 用户token, 根据
     *
     * @param code
     * @return
     */
    public UserTokenResponse getUserToken(String code) {
        UserTokenRequest request = new UserTokenRequest();
        request.setClientId(dingtalkProperties.getAppKey());
        request.setClientSecret(dingtalkProperties.getAppSecret());
        request.setGrantType("authorization_code");
        request.setCode(code);
        return dingtalkTokenClient.getUserToken(request);
    }
}
